package com.my.algorithmlearning.entity;

/**
 * @ClassName ListNode
 * @Description ListNode
 * @Author wanghaiwei
 * @Date 2022/11/22 9:51
 */
public class ListNode {
    public int val;
    public ListNode next;
    private boolean end;
    private boolean cycleStart;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder(String.valueOf(this.val));
        if (this.next == null || this.end) {
            return sb.toString();
        } else {
            sb.append(",").append(this.next);
        }
        return sb.toString();
    }

    public static ListNode convertArrayToListNode(int[] values) {
        if (values == null || values.length == 0) {
            return null;
        }
        ListNode current = new ListNode(values[0]);
        ListNode root = current;
        for (int i = 1; i < values.length; i++) {
            ListNode next = new ListNode(values[i]);
            if (i == values.length - 1) {
                next.setEnd(true);
            }
            current.next = next;
            current = next;
        }
        return root;
    }

    public static ListNode convertArrayToListNode(int[] values, int cyclePos) {
        if (values == null || values.length == 0) {
            return null;
        }
        ListNode current = new ListNode(values[0]);
        ListNode root = current;
        ListNode endNode = null;
        ListNode cyclePosNode = root;
        for (int i = 1; i < values.length; i++) {
            ListNode next = new ListNode(values[i]);
            if (i == values.length - 1) {
                next.setEnd(true);
                endNode = next;
            }
            if (i == cyclePos) {
                cyclePosNode = next;
            }
            current.next = next;
            current = next;
        }
        if (cyclePos >= 0) {
            endNode.next = cyclePosNode;
        }
        return root;
    }

    public boolean isEnd() {
        return end;
    }

    public void setEnd(boolean end) {
        this.end = end;
    }

    public boolean isCycleStart() {
        return cycleStart;
    }

    public void setCycleStart(boolean cycleStart) {
        this.cycleStart = cycleStart;
    }

    public void clearEndFlag() {
        ListNode next = this;
        while(next != null) {
            next.setEnd(false);
            next = next.next;
        }
    }
}
